from select import select
import serial
#from serial import *
import sys
import os
import time
from serial.tools import list_ports

def sticazzi():
    print "prova"

def list_serial_ports():
    # Windows
    if os.name == 'nt':
        # Scan for available ports.
        available = []
        for i in range(256):
            try:
                s = serial.Serial(i)
                #s = Serial(1)
                available.append('COM'+str(i + 1))
                s.close()
            except serial.SerialException:
            #except SerialException:
                pass
        return available
    else:
        # Mac / Linux
        return [port[0] for port in list_ports.comports()]

def PrintUsage():
    print "\n Usage:"
    print "\t python test-serial-echo.py <com_port> <baudrate> <timeout>"
    print "\n"


if __name__ == "__main__":
    if len(sys.argv)!=4:        
        print "Wrong arguments (number)"
        PrintUsage()
        exit(1)
    try:
        print "Using:"
        port = str(sys.argv[1])
        print "- port=",port
        baudrate = int(sys.argv[2])
        print "- baudrate=",str(baudrate)
        timeout = int(sys.argv[3])
        print "- timeout=",str(timeout)
    except:
        print "Wrong arguments (types)"
        PrintUsage()
        print "Available COM ports:\n",list_serial_ports()
        exit(2)
    print "Program for testing serial communication."
    print "Type CTRL+C to exit"

    ##########
    # port             = port
    # baudrate         = 9600
    bytesize         = serial.EIGHTBITS
    parity           = serial.PARITY_NONE
    stopbits         = serial.STOPBITS_ONE
    #timeout          = timeout
    xonxoff          = False
    rtscts           = False
    writeTimeout     = None
    dsrdtr           = False
    interCharTimeout = None

    try:
        ser = serial.Serial( port, baudrate,
                    bytesize, parity, stopbits,
                    timeout, xonxoff, rtscts,
                    writeTimeout, dsrdtr, interCharTimeout )
    except:
        print "Cannot open serial"
        print "Available COM ports:\n",list_serial_ports()
        exit(3)

    i = 0
    run = True
    cd_curr = False
    print "CD =",cd_curr
    while run:
        try:
            #i+=1
            #print i
            time.sleep(0.1)
            if ser.inWaiting()>0:
                print "Echoing data ( size =",ser.inWaiting(),")...",
                ser.write(ser.read(ser.inWaiting()))
                print "Done."
            if ser.getCD()!= cd_curr:
                cd_curr = ser.getCD()
                print "CD changed to", cd_curr
        except (KeyboardInterrupt, SystemExit):
            run = False
    try:
        if ser.isOpen():
            ser.close()
    except:
        print "Cannot close port (never open?)"
    print "Exited"

    
    
